<template>
  <div class="attendance-rules">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{ $t('attendance.rules') }}</span>
      </div>
      
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item :label="$t('course.title')">
          <el-select v-model="selectedCourse" :placeholder="$t('common.pleaseSelect') + ' ' + $t('course.title')" @change="handleCourseChange">
            <el-option
              v-for="course in teacherCourses"
              :key="course.id"
              :label="course.name"
              :value="course">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <el-form 
        v-if="selectedCourse"
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="120px"
        class="rule-form">
        <el-form-item :label="$t('attendance.semesterTime')" required>
          <el-col :span="11">
            <el-form-item prop="semesterStart">
              <el-date-picker
                v-model="ruleForm.semesterStart"
                type="date"
                :placeholder="$t('common.pleaseSelect') + ' ' + $t('attendance.startDate')"
                value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col class="line" :span="2">-</el-col>
          <el-col :span="11">
            <el-form-item prop="semesterEnd">
              <el-date-picker
                v-model="ruleForm.semesterEnd"
                type="date"
                :placeholder="$t('common.pleaseSelect') + ' ' + $t('attendance.endDate')"
                value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-form-item>

        <el-form-item :label="$t('attendance.checkTime')" required>
          <el-col :span="11">
            <el-form-item prop="checkInTime">
              <el-time-picker
                v-model="ruleForm.checkInTime"
                format="HH:mm"
                :placeholder="$t('common.pleaseSelect') + ' ' + $t('attendance.checkTime')"
                value-format="HH:mm">
              </el-time-picker>
            </el-form-item>
          </el-col>
          <el-col class="line" :span="2">-</el-col>
          <el-col :span="11">
            <el-form-item prop="checkInEndTime">
              <el-time-picker
                v-model="ruleForm.checkInEndTime"
                format="HH:mm"
                :placeholder="$t('common.pleaseSelect') + ' ' + $t('attendance.endTime')"
                value-format="HH:mm">
              </el-time-picker>
            </el-form-item>
          </el-col>
        </el-form-item>

        <el-form-item :label="$t('attendance.locationLimit')" prop="locationRequired">
          <el-switch v-model="ruleForm.locationRequired"></el-switch>
        </el-form-item>

        <el-form-item :label="$t('attendance.checkLocation')" v-if="ruleForm.locationRequired">
          <el-col :span="11">
            <el-form-item prop="locationLongitude">
              <el-input v-model="ruleForm.locationLongitude" :placeholder="$t('attendance.longitude')"></el-input>
            </el-form-item>
          </el-col>
          <el-col class="line" :span="2">,</el-col>
          <el-col :span="11">
            <el-form-item prop="locationLatitude">
              <el-input v-model="ruleForm.locationLatitude" :placeholder="$t('attendance.latitude')"></el-input>
            </el-form-item>
          </el-col>
        </el-form-item>

        <el-form-item :label="$t('attendance.distance')" v-if="ruleForm.locationRequired" prop="validDistance">
          <el-input-number 
            v-model="ruleForm.validDistance" 
            :min="1"
            :max="1000"
            :label="$t('attendance.meter')">
          </el-input-number>
          <span class="unit">{{ $t('attendance.meter') }}</span>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">{{ $t('common.save') }}</el-button>
          <el-button @click="resetForm('ruleForm')">{{ $t('common.reset') }}</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import request from '@/utils/request'

export default {
  name: 'AttendanceRules',
  data() {
    return {
      teacherCourses: [],
      selectedCourse: null,
      ruleForm: {
        semesterStart: '',
        semesterEnd: '',
        checkInTime: '',
        checkInEndTime: '',
        locationRequired: false,
        locationLongitude: '',
        locationLatitude: '',
        validDistance: 100
      },
      rules: {
        semesterStart: [
          { required: true, message: this.$t('attendance.selectSemesterStart'), trigger: 'change' }
        ],
        semesterEnd: [
          { required: true, message: this.$t('attendance.selectSemesterEnd'), trigger: 'change' }
        ],
        checkInTime: [
          { required: true, message: this.$t('attendance.selectCheckInTime'), trigger: 'change' }
        ],
        checkInEndTime: [
          { required: true, message: this.$t('attendance.selectCheckInEndTime'), trigger: 'change' }
        ],
        locationLongitude: [
          { required: true, message: this.$t('attendance.inputLongitude'), trigger: 'blur' }
        ],
        locationLatitude: [
          { required: true, message: this.$t('attendance.inputLatitude'), trigger: 'blur' }
        ],
        validDistance: [
          { required: true, message: this.$t('attendance.setValidDistance'), trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    userId() {
      return this.getUserId()
    },
    isUserAdmin() {
      return this.getUserRole() === 'admin'
    },
    isUserTeacher() {
      return this.getUserRole() === 'teacher'
    }
  },
  created() {
    this.getTeacherCourses()
  },
  methods: {
    ...mapGetters(['getUserId', 'getUserRole']),
    async getTeacherCourses() {
      try {
        const userId = this.userId
        
        if (!userId && !this.isUserAdmin) {
          this.$message.error(this.$t('user.loginRequired'))
          return
        }
        
        // 如果是管理员，使用分页接口获取所有课程
        const apiPath = this.isUserAdmin ? '/course/page' : `/course/teacher/${userId}`
        
        const res = await request.get(apiPath)
        if (res.code === 200) {
          // 根据接口返回的数据格式处理
          if (this.isUserAdmin) {
            // 管理员使用分页接口，数据在data字段中
            this.teacherCourses = res.data.records || []
          } else {
            // 教师直接获取课程列表
            this.teacherCourses = res.data || []
          }
          //console.log(this.teacherCourses);
        } else {
          this.$message.error(res.msg || this.$t('course.getCoursesError'))
        }
      } catch (error) {
        console.error('获取课程列表失败:', error)
        this.$message.error(this.$t('course.getCoursesError'))
      }
    },
    async handleCourseChange(course) {
      if (course) {
        try {
          // 保存完整的课程对象而不仅是名称
          this.selectedCourse = course
          
          // 使用您的request工具
          const res = await request.get('/attendance/config/course', {
            params: { courseId: course.id }
          })
          
          let config = res.data

          if (config) {
            //console.log('找到配置数据:', config)
            
            this.ruleForm = {
              semesterStart: config.semesterStart || '',
              semesterEnd: config.semesterEnd || '',
              checkInTime: typeof config.checkInTime === 'string' ? config.checkInTime.substring(0, 5) : '',
              checkInEndTime: typeof config.checkInEndTime === 'string' ? config.checkInEndTime.substring(0, 5) : '',
              locationRequired: !!config.locationRequired,
              locationLongitude: config.locationLongitude || '',
              locationLatitude: config.locationLatitude || '',
              validDistance: config.validDistance || 100
            }
            
            //console.log('设置表单数据:', this.ruleForm)
          } else {
            this.resetForm('ruleForm')
            this.$message.warning(res.msg || this.$t('attendance.noConfigFound'))
          }
        } catch (error) {
          console.error('获取课程考勤配置失败:', error)
          this.$message.error(this.$t('attendance.getConfigError'))
        }
      } else {
        this.resetForm('ruleForm')
      }
    },
    formatTime(time) {
      if (!time) return ''
      const hour = time.hour.toString().padStart(2, '0')
      const minute = time.minute.toString().padStart(2, '0')
      return `${hour}:${minute}`
    },
    parseTime(timeStr) {
      if (!timeStr) return null
      const [hour, minute] = timeStr.split(':').map(Number)
      return `${hour}:${minute}`
    },
    async submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          try {
            // 验证时间范围
            if (this.ruleForm.checkInTime >= this.ruleForm.checkInEndTime) {
              this.$message.error(this.$t('attendance.checkInTimeError'))
              return
            }
            
            // 验证学期时间范围
            if (this.ruleForm.semesterStart >= this.ruleForm.semesterEnd) {
              this.$message.error(this.$t('attendance.semesterTimeError'))
              return
            }
            
            const config = {
              courseId: this.selectedCourse.id,
              semesterStart: this.ruleForm.semesterStart,
              semesterEnd: this.ruleForm.semesterEnd,
              checkInTime: this.ruleForm.checkInTime,
              checkInEndTime: this.ruleForm.checkInEndTime,
              locationRequired: this.ruleForm.locationRequired,
              locationLongitude: this.ruleForm.locationLongitude ? parseFloat(this.ruleForm.locationLongitude) : null,
              locationLatitude: this.ruleForm.locationLatitude ? parseFloat(this.ruleForm.locationLatitude) : null,
              validDistance: parseInt(this.ruleForm.validDistance)
            }
            
            // 如果选择了位置要求，验证经纬度是否已填写
            if (config.locationRequired && (!config.locationLongitude || !config.locationLatitude)) {
              this.$message.error(this.$t('attendance.locationRequiredError'))
              return
            }
            
            const res = await request.post('/attendance/config/course', config)
            
            if (res.code === 200) {
              this.$message.success(this.$t('attendance.configSaveSuccess'))
              // 重新获取当前课程的配置
              if (this.selectedCourse) {
                this.handleCourseChange(this.selectedCourse)
              }
            } else {
              this.$message.error(res.msg || this.$t('attendance.configSaveError'))
            }
          } catch (error) {
            console.error('考勤规则设置失败:', error)
            this.$message.error(this.$t('attendance.configSaveError'))
          }
        } else {
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.ruleForm = {
        semesterStart: '',
        semesterEnd: '',
        checkInTime: '',
        checkInEndTime: '',
        locationRequired: false,
        locationLongitude: '',
        locationLatitude: '',
        validDistance: 100
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.attendance-rules {
  padding: 20px;
  
  .rule-form {
    margin-top: 20px;
    max-width: 800px;
  }
  
  .line {
    text-align: center;
    line-height: 40px;
  }
  
  .unit {
    margin-left: 10px;
  }
}
</style> 